#include "app_pool.h"


static mqd_t mqd;

static char *mq_name = "/app_pool_mq";
static int thread_num = 0;
static pthread_t *thread_pool;

void *pool_thread_func(void *arg){
    Task task;
    while(1){
       size_t len = mq_receive(mqd, (char *)&task, sizeof(Task), NULL);
       if (len == sizeof(Task))
       {
            task.task_func(task.arg);
       }
       
    }
    return NULL;
}

/**
 * @brief 线程池初始化
 * 
 * @param size 创建线程的个数
 * @return int 返回值为0表示成功，-1表示失败
 */
int app_pool_init(int size){
    //创建消息任务队列
    struct mq_attr attr;
    attr.mq_maxmsg = 5;
    attr.mq_msgsize = sizeof(Task);
    mqd = mq_open(mq_name, O_CREAT | O_RDWR, 0666, &attr);

    if (mqd == -1)
    {
        printf("mq_open error\n");
        return -1;
    }
    
    //初始化线程池
    thread_num = size;
    thread_pool = (pthread_t *)malloc(sizeof(pthread_t) * size);
    for(int i = 0; i < size; i++){
       pthread_create(thread_pool + i, NULL, pool_thread_func, NULL);
        

        
    }
    
    return 0;
}

/**
 * @brief 关闭线程池
 * 
 */
void app_pool_close(void){
    for (int i = 0; i < thread_num; i++)
    {
        pthread_cancel(thread_pool[i]);
        pthread_join(thread_pool[i], NULL);
        
    }
    free(thread_pool);
    mq_close(mqd);
    mq_unlink(mq_name);
}
/**
 * @brief 注册任务
 * 
 * @param task  任务函数
 * @param arg 任务函数的参数
 * @return int 是否注册成功0表示成功，-1表示失败
 */
void app_pool_registerTask(int (*task_func)(void *arg), void *arg){
    Task task={
        .task_func = task_func,
        .arg = arg
    };
    mq_send(mqd, (char *)&task, sizeof(Task), 0);
}
